import Vue from 'vue'
import VueRouter from 'vue-router'
import { instance2 } from '@/utils/http'
Vue.use(VueRouter) // 让vue使用vue-router这个插件
const routes = [
  {
    path: '/films',
    component: () => import('@/views/films'), // 返回一个Promise实例，只要真正想让其渲染出界面中，才会去异步解析模板。
    children: [
      { path: '/films/nowplaying', component: () => import('@/views/films/nowplaying') },
      { path: '/films/comingsoon', component: () => import('@/views/films/comingsoon'), name: 'cs' },
      { path: '/films', redirect: '/films/nowplaying' } // 已进入films中，匹配到了，直接重定向到正在热映页面
    ]
  },
  {
    path: '/detail/:id',
    component: () => import(/* webpackChunkName: "detail" */ '@/views/detail')
  },
  { path: '/cinema', component: () => import('@/views/cinema') },
  { path: '/city', component: () => import('@/views/city') },
  {
    path: '/cinema/search',
    component: () => import('@/views/search'),
    meta: {
      isTabbar: true // 哪一个路由不需要显示tabbar的话，只需要添加此属性即可
    }
  },
  {
    path: '/center',
    component: () => import('@/views/center'),
    meta: { requiresAuth: true }
  },
  { path: '/login', component: () => import('@/views/login') },
  { path: '/', redirect: '/films' }, // 一进来首页，重定向到films中
  { path: '*', redirect: '/films' } // 如果上述路由没有匹配到，还是重定向到films中
]
const router = new VueRouter({
  mode: 'history',
  base: '/maizuo',
  routes
})

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!localStorage.getItem('token')) { // 本地存储中没有token
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    } else {
      // token存在本地了，但是token失效的处理
      instance2.post('/api/user/issignin').then(res => {
        next()
      }).catch(() => {
        next({
          path: '/login',
          query: { redirect: to.fullPath }
        })
      })
    }
  } else {
    next() // 确保一定要调用 next()
  }
})
export default router
